import siteinfo from '../siteinfo.js'
export const util = {
    request: function (option) {
        var site_id = siteinfo.site_id
        // #ifdef WEB
        site_id = window.site_id
        // #endif
        option = option ? option : {};
        // 组装url
        var url = option.url;
		
		//修改#########################################
		//如果option 有 option-site   ,把对应的值修改到url  ,原有的请求不做变化
		//url = siteinfo.host +  option.site + option.url;  通常为 ai对话：/web.php ai剪辑： /small.php
		var sitePre='/api.php'
		var xToken=uni.getStorageSync('token')
		//站点不同，对应的的x-token也不同，需要替换，登录的时候对三个平台登录，保存token- 一个失效后都再登录一次
		//x-token=uni.getStorageSync('token'); 其他站点  uni.getStorageSync('token-web'), uni.getStorageSync('token-small')
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = siteinfo.host + sitePre + option.url;
            // #ifdef WEB
            url = sitePre + option.url;
            // #endif
        }
        if (!url) {
            return false;
        }

        // 是否显示loading
        option.loading = option.loading !== false;
        if (option.loading) {
            uni.showLoading({
                title: option.loadingText || '加载中'
            });
        }
        var data = option.data ? option.data : {};
        return new Promise(function (resolve, reject) {
            uni.request({
                url: url,
                data: data,
                method: option.method ? option.method : 'POST',
                dataType: 'json',
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Token': xToken,
                    'Site-id': site_id
                },
                timeout: option.timeout ? option.timeout : 60000,
                success: function (res) {
                    if (res.statusCode !== 200) {
                        // util.message('网络错误1' + url);
                        reject(res);
                        return;
                    }
                    if (res.data.errno > 0) {
                        if (res.data.errno === 403) {
                            if (option.url !== '/user/checkLogin') {
                                util.toLogin(res.data.message)
                            }
                        } else {
                            util.message(res.data.message || '接口异常', 'error');
                        }

                        reject(res.data);
                    } else {
                        resolve(res.data);
                    }
                },
                fail: function (err) {
                    util.message('当前网络较差，请稍后重试');
                    reject(err);
                },
                complete: function (res) {
                    if (option.loading) {
                        uni.hideLoading();
                        uni.hideNavigationBarLoading();
                    }
                }
            });
        });
    },
    upload: function (option = null) {
        var site_id = siteinfo.site_id
        // #ifdef WEB
        site_id = window.site_id
        // #endif

        option = option ? option : {};
        // 组装url
        var url = option.url;
		//修改#########################################
		//如果option 有 option-site   ,把对应的值修改到url  ,原有的请求不做变化
		//url = siteinfo.host +  option.site + option.url;  通常为 ai对话：/web.php ai剪辑： /small.php
		var sitePre='/api.php'
		var xToken=uni.getStorageSync('token')
		//站点不同，对应的的x-token也不同，需要替换，登录的时候对三个平台登录，保存token- 一个失效后都再登录一次
		//x-token=uni.getStorageSync('token'); 其他站点  uni.getStorageSync('token-web'), uni.getStorageSync('token-small')
        if (url.indexOf('http://') === -1 && url.indexOf('https://') === -1) {
            url = siteinfo.host + '/api.php' + option.url;
            // #ifdef WEB
            url = '/api.php' + option.url;
            // #endif
        }
        if (!url) {
            return false;
        }

        // 是否显示loading
        option.loading = option.loading !== false;
        if (option.loading) {
            uni.showLoading({
                title: option.loadingText || '上传中'
            });
        }
        return new Promise(function (resolve, reject) {
            var uploadTask = uni.uploadFile({
                url: url,
                filePath: option.filePath,
                name: option.name ? option.name : 'file',
                formData: option.data ? option.data : {},
                header: {
                    'X-Token': uni.getStorageSync('token'),
                    'Site-id': site_id
                },
                dataType: 'json',
                timeout: option.timeout ? option.timeout : 120000,
                success: function (response) {
                    if (response.statusCode === 413) {
                        reject({
                            message: '上传失败：文件大小超过限制'
                        })
                        return
                    }
                    try {
                        const res = JSON.parse(response.data);
                        if (res.errno > 0) {
                            if (res.errno === 403) {
                                // 需要登录后才可以操作
                                util.toLogin('请登录');
                            } else {
                                if (res.message && res.message.indexOf('请充值') === -1) {
                                    util.message(res.message, 'error');
                                }
                            }
                            reject(res)
                        } else {
                            resolve(res.data)
                        }
                    } catch (e) {
                        util.message('上传失败：网络错误');
                        reject()
                    }
                },
                fail: function (err) {
                    util.message('当前网络较差，请稍后重试', 'error');
                    reject(res);
                },
                complete: function (res) {
                    if (option.loading) {
                        uni.hideLoading();
                    }
                }
            });
            if (option.onProgressUpdate) {
                uploadTask.onProgressUpdate(res => {
                    option.onProgressUpdate(res)
                })
            }
        });
    },
    toLogin: function (message = '') {
        var loginUrl = '/pages/login/login'
        // #ifdef WEB
        loginUrl = '/pages/login/login-code'
        // #endif
        if (message) {
            util.confirm(message, '去登录', function() {
                uni.navigateTo({
                    url: loginUrl
                })
            })
        } else {
            uni.navigateTo({
                url: loginUrl
            })
        }
    },
    toPay: function (type = 'vip', message = '') {
        if (message) {
            util.confirm(message, '去充值', function() {
                uni.navigateTo({
                    url: '/pages/pay/pay?type=' + type
                })
            })
        } else {
            uni.navigateTo({
                url: '/pages/pay/pay?type=' + type
            })
        }
    },
    confirm: function(message, confirmText = '', callback = null) {
        uni.showModal({
            title: '提示',
            content: message,
            confirmText: confirmText ? confirmText : '确定',
            cancelText: '取消',
            success: function (res) {
                if (res.confirm && callback && typeof callback == 'function') {
                    callback()
                }
            }
        })
    },
    message: function (title, type = 'none', callback = null) {
        if (!title) {
            return true;
        }
        if (type === 'success') {
            uni.showToast({
                title: title,
                icon: 'success',
                duration: 2000,
                mask: false,
                complete: function () {
                    if (callback && typeof callback == 'function') {
                        setTimeout(function () {
                            callback();
                        }, 1800);
                    }
                }
            });
        } else if (type === 'none') {
            uni.showToast({
                title: title,
                icon: 'none',
                duration: 2000,
                mask: false,
                complete: function () {
                    if (callback && typeof callback == 'function') {
                        setTimeout(function () {
                            callback();
                        }, 1800);
                    }
                }
            });
        } else if (type === 'error') {
            uni.showModal({
                title: '提示',
                content: title,
                showCancel: false,
                confirmText: '确定',
                complete: function () {
                    if (callback && typeof callback == 'function') {
                        callback();
                    }
                }
            });
        }
    },
    openUrl(url) {
        if (!url) {
            return
        }
        if (url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1) {
            uni.navigateTo({
                url: '/pages/webview/webview?url=' + encodeURIComponent(url)
            });
        } else {
            uni.navigateTo({
                url: url,
                fail: function () {
                    uni.switchTab({
                        url: url
                    })
                }
            })
        }
    },
    checkLogin: function () {
        return new Promise(function (resolve, reject) {
            util.request({
                url: '/user/checkLogin',
                loading: false
            })
                .then((res) => {
                    if (res.errno === 403) {
                        reject(res)
                    } else {
                        resolve(res)
                    }
                })
                .catch((res) => {
                    reject(res)
                });
        });
    },
    queryToArr: function (str) {
        let result = [];
        let kv = [];
        let paramArr = str.split('&');
        for (let i in paramArr) {
            kv = paramArr[i].split('=');
            result[kv[0]] = kv[1];
        }
        return result;
    },
    isMobile: function(mobile) {
        return /^1([3589]\d|4[5-9]|6[1-2,4-7]|7[0-8])\d{8}$/.test(mobile);
    },
    deepClone: function(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        let clone;
        if (obj instanceof Date) {
            clone = new Date(obj.getTime());
        } else if (obj instanceof RegExp) {
            clone = new RegExp(obj);
        } else if (obj instanceof Map) {
            clone = new Map(Array.from(obj, ([key, value]) => [key, deepClone(value)]));
        } else if (obj instanceof Set) {
            clone = new Set(Array.from(obj, value => deepClone(value)));
        } else if (Array.isArray(obj)) {
            clone = obj.map(value => deepClone(value));
        } else if (Object.prototype.toString.call(obj) === '[object Object]') {
            clone = Object.create(Object.getPrototypeOf(obj));
            for (const [key, value] of Object.entries(obj)) {
                clone[key] = deepClone(value);
            }
        } else {
            clone = Object.assign({}, obj);
        }
        return clone;
    },
    hexToRgba: function(hexColor, alpha = 1) {
        if (!hexColor) {
            return '';
        }
        hexColor = hexColor.replace('#', '');
        var red = parseInt(hexColor.substring(0, 2), 16);
        var green = parseInt(hexColor.substring(2, 4), 16);
        var blue = parseInt(hexColor.substring(4, 6), 16);
        return 'rgba(' + red + ',' + green + ',' + blue + ',' + alpha + ')';
    },
    isNumber: function (val) {
        return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(val);
    }

};

